package cn.bxshey.modules_commodity.strategy.coupons;

import cn.bxshey.general.entity.CouponsType;
import cn.bxshey.modules_commodity.service.CouponsService;
import cn.bxshey.modules_commodity.service.CouponsTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @作者：不想说话而已
 * @Date：2024/2/19 1:28
 */

@Component
public class StrategyFactory {

    private final CouponsTypeService couponsTypeService;

    private final static Map<String, Strategy> STRATEGY_MAP = new ConcurrentHashMap<>();

    private static final Map<String, String> dictionary = new ConcurrentHashMap<>();

    @Autowired
    public StrategyFactory(CouponsTypeService couponsTypeService) {
        this.couponsTypeService = couponsTypeService;
    }

    /**
     * 通过类型获得具体的策略
     *
     * @param type 类型
     * @return 策略实现类
     */
    public static Strategy getStrategy(String type) {
        return STRATEGY_MAP.get(type);
    }

    //初始字典，加载所有优惠卷类型
    @PostConstruct
    public void init() {
        List<CouponsType> all = couponsTypeService.getAll();
        all.forEach(s -> {
            dictionary.put(String.valueOf(s.getCouponsTypeId()), s.getCouponsTypeMessage());
        });
    }

    /**
     * 注册策略--初始化
     */
    public static void register(String type, Strategy handler) {
        if (handler == null && Objects.isNull(type) || type.equals("")) {
            return;
        }
        STRATEGY_MAP.put(type, handler);
    }


    //是否存在该类型
    public static boolean is(String key) {
        if ((Objects.isNull(key) && key == null) || key.isEmpty()) {
            return false;
        }
        return dictionary.containsKey(key);
    }


}
